package cn.hh.wechatkit.pojo.jssdk;


import cn.hh.wechatkit.helper.CacheHelper;
import cn.hh.wechatkit.param.WxParam;
import cn.hh.wechatkit.util.WxSignUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created this one by HMH on 2017/4/5.
 */
public class WxJSSDK_Config {

    private final static Logger logger = LoggerFactory.getLogger(WxJSSDK_Config.class);

    public static JsConfigObject getConfig(String url , String... list) {
        boolean debug = false;
        String appId = WxParam.appId;
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        String noncestr = String.valueOf(RandomUtils.nextLong(1,500000000L));

        String signature = WxSignUtil.signaure("&", JsConfigObject.toParam(CacheHelper.getJsApiToken().getTicket(), noncestr,timestamp,url));

        JsConfigObject jsConfigObject = new JsConfigObject(debug, appId, timestamp, noncestr, signature, list);
        String config = JSON.toJSONString(jsConfigObject);
        logger.debug("生成签名: ",config);
        return jsConfigObject;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    static public class JsConfigObject {
        boolean debug ;
        String appId ;
        String timestamp ;
        String nonceStr;
        String signature;
        String[] jsApiList;

        static String[] toParam(String jsapi_ticket, String noncestr, String timestamp, String url) {
            String[] list = new String[4];
            list[0] = "timestamp=" + timestamp;
            list[1] = "noncestr=" + noncestr;
            list[2] = "url=" + url;
            list[3] = "jsapi_ticket=" + jsapi_ticket;
            return list;
        }
    }
}
